package org.zjx.core;

import lombok.Data;
import org.zjx.listener.EventListener;
import org.zjx.state.IDataState;
import org.zjx.state.StateManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Data
public class GameContext {

    private Map<String, List<EventListener>> listeners;

    private final Map<Class<? extends IDataState>, IDataState> stateMap = new HashMap<>();

    private StateManager stateManager;


    public GameContext() {
        listeners = new ConcurrentHashMap<>();
        stateManager = new StateManager();
    }

    public List<String> getKeys() {
        return new ArrayList<>(listeners.keySet());
    }

    public void addListener(String name, EventListener listener) {
        listeners.computeIfAbsent(name, k -> new ArrayList<>()).add(listener);
    }

    public void removeListener(String name, EventListener listener) {
        listeners.computeIfAbsent(name, k -> new ArrayList<>()).remove(listener);
        if (listeners.get(name).isEmpty()) listeners.remove(name);
    }

    public void notifyListeners(String name, Object o) {
        if (!listeners.containsKey(name)) return;
        for (EventListener listener : listeners.computeIfAbsent(name, k -> new ArrayList<>())) {
            listener.onEvent(o);
        }
    }
}
